package librss;
import java.io.File;
import java.util.Iterator;
import java.util.Vector;

/*
 * Feed.java
 *
 * Created on March 7, 2009, 12:23 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author alvaro
 */
public class Feed {
    
    private RSSParser parser;
    private Constantes cons;
    private String prefix;
    
    /** Creates a new instance of Feed */
    public Feed(String prefix, String configFile) throws Exception {
        if(!prefix.endsWith("/") && !prefix.endsWith("\\")){
            prefix = prefix.concat(System.getProperty("file.separator"));
        }
        this.prefix = prefix;
        cons = new Constantes(prefix, configFile);
    }
    
    public boolean checkNewItem() throws Exception {
        boolean newitem = false;
        File f = new File(cons.LOCAL_FILE);
        //descarga
        DownloadPage.download(cons.RSS_URL, cons.NET_FILE);
        if(!f.exists()){
            replaceLocalByNet();
            if(parser.getItemsNumber() > 0)
                return true;
            else
                return false;
        }
        RSSParser local = new RSSParser(cons.LOCAL_FILE);
        RSSParser net = new RSSParser(cons.NET_FILE);
        if(net.getItemsNumber() == 0){
            replaceLocalByNet();
            return false;
        }
        if(local.getItemsNumber() == 0){
            replaceLocalByNet();
            return true;
        }
        if(local.getItemAt(0).compareTo(net.getItemAt(0)) >= 0){
            replaceLocalByNet();
            return false;
        }else{
            replaceLocalByNet();
            return true;
        }
    }
    
    private void replaceLocalByNet() throws Exception {
        File f = new File(cons.LOCAL_FILE);
        f.delete();
        f = new File(cons.NET_FILE);
        f.renameTo(new File(cons.LOCAL_FILE));
        parser = new RSSParser(cons.LOCAL_FILE);
    }
    
    public Vector<RSSItem> getItemsByTag(String tag) throws Exception {
        Vector<RSSItem> vec = this.getAllItems();
         if(vec == null)
            return null;
       
        //RSSItem item = null;
        //int counter = 0;
        for(int i = 0;i<vec.size();i++){
            if(!vec.get(i).getTags().contains(tag)){
                vec.remove(i);
                i = 0;
            }
        }
        return vec;
    }
    
    public Vector<RSSItem> getAllItems() throws Exception{
        if(parser == null)
            return null;
        return parser.getVector();
    }
}
